﻿using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;

namespace VueShopApi.Common.Extensions
{
    public static class AuthenticateHttpContextExtensions
    {
        public static string GetBearerToken(this HttpContext httpContext, string headerKey = "Authorization")
        {
            if (httpContext.Request.Headers.ContainsKey(headerKey))
                return httpContext.Request.Headers[headerKey];
            return null;
        }

        public static ManagerPrincipal GetClaimsPrincipal(this HttpContext httpContext, string headerKey = "Authorization")
        {
            var token = httpContext.GetBearerToken(headerKey);
            if (string.IsNullOrWhiteSpace(token)) return null;

            var tokenStr = token.Replace("Bearer ", "");
            var handler = new JwtSecurityTokenHandler();
            if (handler.CanReadToken(tokenStr))
            {
                var payload = handler.ReadJwtToken(tokenStr).Payload;
                var claim = payload.Claims.FirstOrDefault(claim => claim.Type == "Principal")?.Value;
                return JsonConvert.DeserializeObject<ManagerPrincipal>(claim);
            }
            return null;
        }
    }
}
